const {
  Sequelize,
  Model
} = require('sequelize')
const bcrypt = require('bcryptjs')
const {
  sequelize
} = require('@root/core/db')

class User extends Model {
  /**
   * 登录用户信息验证
   * @static
   * @param {*} username
   * @param {*} password
   * @memberof User
   */
  static async verfiyUserNamePassword(username, password) {
    const user = await User.findOne({
      where: {
        username
      }
    })
    if(!user) {
      throw new global.errors.AuthFailed('用户名或密码错误')
    }
    // 用户名正确验证密码
    const correct = bcrypt.compareSync(password, user.password)
    if (!correct) {
      throw new global.errors.AuthFailed('用户名或密码错误')
    }
    return user
  }

  /**
   * 用户登录
   * @static
   * @param {*} username
   * @param {*} password
   * @memberof User
   */
  static async login(username, password) {

  }
}

User.init({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  username: {
    type: Sequelize.STRING(32),
    allowNull: false,
    unique: true
  },
  nickname: {
    type: Sequelize.STRING(32),
    allowNull: false,
    unique: true
  },
  password: {
    type: Sequelize.STRING,
    set(val) {
        const salt = bcrypt.genSaltSync(10)
        const psw = bcrypt.hashSync(val, salt)
        this.setDataValue('password', psw)
    }
  },
}, {
  sequelize,
  tableName: 'user'
})

module.exports = {
  User
}
